package com.szgd.service.equipment;

import com.szgd.bean.SysDict;
import com.szgd.dao.ecdata.equipment.EquipmentMapper;
import com.szgd.paging.Order;
import com.szgd.paging.PageBounds;
import com.szgd.service.sys.DeptService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.Constant;
import com.szgd.util.StringUtil;
import com.szgd.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class EquipmentService extends SimulateBaseService {

    @Autowired
    EquipmentMapper equipmentMapper;
    @Autowired
    SysDictService sysDictService;
    @Autowired
    DeptService deptService;

    public List<Map<String, Object>> getEquipmentInfoListNoPage(Map<String, Object> params) {
        List<Map<String, Object>>  equipmentInfoList = equipmentMapper.getEquipmentList(params);
        return equipmentInfoList;
    }

    public int getEquipmentCount(Map<String, Object> params) {
        return  equipmentMapper.getEquipmentCount(params);
    }

    public List<Map<String, Object>> getEquipmentInfoList(Map<String, Object> params) {
        String sortColumn = "ID"; //默认的排序列
        String sortType = "DESC";
        String iSortCol_0 = (String) params.get("iSortCol_0");	//排序字段，前台传进来的为数值，列从0开始
        String sSortDir_0 = (String) params.get("sSortDir_0");	//排序类型，asc或desc
        if(StringUtil.isNotBlank(iSortCol_0) && StringUtil.isNotBlank(sSortDir_0)){
            sortColumn = (String) params.get("mDataProp_" + iSortCol_0);
            sortType = sSortDir_0;
        }
        String sortString = sortColumn + "." + sortType;	//排序字段及排序类型
        PageBounds pageBounds = new PageBounds(params, Order.formString(sortString));	//绑定排序及相关参数
        List<Map<String, Object>>  equipmentInfoList = getSqlSession().selectList("com.szgd.dao.ecdata.equipment.EquipmentMapper.getEquipmentList", params,pageBounds);

        return equipmentInfoList;
    }

    public Map<String, Object> getEquipment(Map<String, Object> params) {
        List<Map<String,Object>>  list = equipmentMapper.getEquipmentList(params);
        if (list != null && list.size() >0){
            return  list.get(0);
        }
        else {
            return null;
        }
    }

    public Map<String, Object> getEquipment(String id) {
        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("id",id);
        List<Map<String,Object>> equipmentList = equipmentMapper.getEquipmentList(paramsMap);
        if (equipmentList == null || equipmentList.size() == 0) {
            return null;
        }
        return equipmentList.get(0);
    }


    public void insertEquipment(Map<String, Object> paramsMap) {
        equipmentMapper.insertEquipment(paramsMap);
    }

    public void updateEquipment(Map<String, Object> paramsMap) {
        equipmentMapper.updateEquipment(paramsMap);
    }

    public void deleteEquipment(Map<String, Object> paramsMap) {
        equipmentMapper.deleteEquipment(paramsMap);
    }

    public Map<String, String> getFieldMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("equipNumber","设备编号");
        fieldMapping.put("equipType","设备型号");
        fieldMapping.put("name","设备名称");
        fieldMapping.put("useDept","租赁/自有");
        fieldMapping.put("inCharge","操作人");
        fieldMapping.put("testDate","检测日期");
        fieldMapping.put("insuranceExpireDate","保险到期");

        return fieldMapping;
    }

    public Map<String, Object> batchImportEquipInfo(List<Map<String, Object>> equipList,String userId,String batchNo) {
        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String, Object>> successList = new ArrayList<>();   //记录导入成功的数据
        List<Map<String, Object>> updateList = new ArrayList<>();   //记录更新的数据
        List<Map<String, Object>> failedList = new ArrayList<>();   //记录导入失败的数据
        List<Map<String, Object>> ignoreList = new ArrayList<>();   //记录忽略的数据


        for (Map<String, Object> equipMap : equipList) {

            HashMap<String, Object> sourceDataMap = new HashMap<>(equipMap);
            try {
                //***************判断必填项是否为空********************//
                if(equipMap.get("equipNumber") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("equipNumber")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","设备编号为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(equipMap.get("equipType") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("equipType")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","设备型号为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }
                if(equipMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("name")))) {
                }else{
                    sourceDataMap.put("ERROR_MSG","设备名称为必填项");
                    failedList.add(sourceDataMap);
                    continue;
                }

                //***************设备名称********************//
                if(equipMap.get("name") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("name")))) {
                    equipMap.put("PARENT_CODE", "EQUIP_NAME");
                    equipMap.put("DICT_VALUE", equipMap.get("name"));
                    List<SysDict> nameList = sysDictService.getAllSysDict(equipMap);
                    if (nameList != null && nameList.size() > 0) {
                        SysDict dict = nameList.get(0);
                        equipMap.put("name", dict.getCode());
                    } else {
                        sourceDataMap.put("ERROR_MSG","设备名称填写不正确(参考数据字典)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //***************租赁/自有********************//
                if(equipMap.get("useDept") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("useDept")))) {
                    String useDept = String.valueOf(equipMap.get("useDept"));
                    if (useDept.equalsIgnoreCase("租赁"))
                        equipMap.put("useDept",0);
                    else if (useDept.equalsIgnoreCase("自有"))
                        equipMap.put("useDept",1);
                    else
                    {
                        sourceDataMap.put("ERROR_MSG","租赁/自有填写不正确(租赁/自有)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }

                //***************验证日期是否准确********************//
                if(equipMap.get("testDate") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("testDate")))) {
                    String testDate = equipMap.get("testDate").toString();
                    boolean res = TimeUtil.isValidDate(testDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","检测日期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }
                if(equipMap.get("insuranceExpireDate") != null && StringUtil.isNotBlank(String.valueOf(equipMap.get("insuranceExpireDate")))) {
                    String insuranceExpireDate = equipMap.get("insuranceExpireDate").toString();
                    boolean res = TimeUtil.isValidDate(insuranceExpireDate);
                    if(res == false){
                        sourceDataMap.put("ERROR_MSG","保险到期填写不正确(格式YYYY-MM-DD)");
                        failedList.add(sourceDataMap);
                        continue;
                    }
                }



                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("equipNumber",equipMap.get("equipNumber"));
                List<Map<String, Object>> equipInfoList =  this.getEquipmentInfoListNoPage(paramMap);
                if (equipInfoList != null && equipInfoList.size() > 0){
                    equipMap.put("id",equipInfoList.get(0).get("id"));
                    equipMap.put("uploader",userId);
                    equipmentMapper.updateEquipment(equipMap);
                    updateList.add(equipMap);
                }
                else {
                    equipMap.put("creator",userId);
                    equipmentMapper.insertEquipment(equipMap);
                    successList.add(equipMap);
                }

            }catch (Exception e){
                String errorMsg = e.getMessage();
                if(errorMsg.indexOf("###",10) != -1){
                    errorMsg = errorMsg.substring(0,errorMsg.indexOf("###",10));
                }
                sourceDataMap.put("ERROR_MSG",errorMsg);
                //记录导入失败记录
                failedList.add(sourceDataMap);
            }
        }

        //组装本次导入的结果
        resultMap.put(Constant.IMPORT_HE_SUCCESS,successList);
        resultMap.put(Constant.IMPORT_HE_IGNORE,ignoreList);
        resultMap.put(Constant.IMPORT_HE_FAILED,failedList);
        resultMap.put(Constant.IMPORT_HE_UPDATED,updateList);
        return resultMap;
    }

    public Map<String, String> getLogMap(){
        Map<String, String> fieldMapping = new LinkedHashMap<>();

        fieldMapping.put("bidName","标段");
        fieldMapping.put("siteName","站点");
        fieldMapping.put("equipNumber","设备编号");
        fieldMapping.put("equipName","设备名称");
        fieldMapping.put("equipType","设备型号");
        fieldMapping.put("useDept","租赁/自有");
        fieldMapping.put("testDate","检测时期");
        fieldMapping.put("insuranceExpireDate","保险到期");
        fieldMapping.put("haveAccept","是否有设备验收单");
        fieldMapping.put("haveTesting","是否有检测报告");
        fieldMapping.put("haveHoisting","是否有吊装令");
        fieldMapping.put("hoistUploadTime","吊装令上传时间");
        fieldMapping.put("enterTime","进场时间");
        fieldMapping.put("exitTime","出场时间");

        return fieldMapping;
    }

    public List<Map<String, Object>> getEquipmentExcel(Map<String, Object> params) {
        List<Map<String, Object>> equipList = equipmentMapper.getEquipmentExcel(params);
        if (equipList != null)
        {
            for(int i = 0; i < equipList.size(); i++){
                Map<String, Object> equipMap = equipList.get(i);
                String useDept = equipMap.get("useDept")==null?"":equipMap.get("useDept").toString();
                if(useDept.equalsIgnoreCase("0")){
                    equipMap.put("useDept","租赁");
                }else if(useDept.equalsIgnoreCase("1")){
                    equipMap.put("useDept","自有");
                }
                String haveAccept = equipMap.get("haveAccept")==null?"":equipMap.get("haveAccept").toString();
                if(haveAccept.equalsIgnoreCase("0")){
                    equipMap.put("haveAccept","否");
                }else if(haveAccept.equalsIgnoreCase("1")){
                    equipMap.put("haveAccept","是");
                }
                String haveHoisting = equipMap.get("haveHoisting")==null?"":equipMap.get("haveHoisting").toString();
                if(haveHoisting.equalsIgnoreCase("0")){
                    equipMap.put("haveHoisting","否");
                }else if(haveHoisting.equalsIgnoreCase("1")){
                    equipMap.put("haveHoisting","是");
                }
                String haveTesting = equipMap.get("haveTesting")==null?"":equipMap.get("haveTesting").toString();
                if(haveTesting.equalsIgnoreCase("0")){
                    equipMap.put("haveTesting","否");
                }else if(haveTesting.equalsIgnoreCase("1")){
                    equipMap.put("haveTesting","是");
                }
            }
        }
        return equipList;
    }

    public List<Map<String,Object>> getAppEquipmentList(Map<String,Object> params){
        return equipmentMapper.getAppEquipmentList(params);
    }

    public int getAppEquipmentCount(Map<String,Object> params){
        return equipmentMapper.getAppEquipmentCount(params);
    }
}
